package com.sd.repay.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;
import java.util.Date;


/**
 * 描述：重复提交校验
 * <p>
 * 创建时间：2018年8月13日
 */

public class DuplicateSubmitCheck {
    private static final Logger log = LoggerFactory.getLogger(DuplicateSubmitCheck.class);
    private static final String DUPLICATE_TIMESTAMP = "duplicateTimeStamp";
    private static Object lock = new Object();

    /**
     * 设置重复提交控制时间戳：0：交易未提交 1：交易已经提交
     */
    public String setDuplicateTime(HttpSession session) {
        String duplicateTimeStamp = "" + new Date().getTime() + (int) (Math.random() * 100000000);
        session.setAttribute(duplicateTimeStamp, "0");
        return duplicateTimeStamp;
    }


    /**
     * 验证是否为重复提交交易
     */
    public Boolean verifyDuplicate(HttpSession session, String duplicateTimeStamp) {
        String duplicateFlag = (String) session.getAttribute(duplicateTimeStamp);
        if (StringUtils.isBlank(duplicateFlag)) {
            log.error("重复提交控制时间戳为空或不存在");
            return false;
        }
        synchronized (lock) {
            if ("0".equals(duplicateFlag)) {
                session.setAttribute(duplicateTimeStamp, "1");
                return true;
            } else {
                log.error("请勿重复提交");
                return false;
            }
        }
    }


}
